// pages/index/index.js
const app = getApp();

Page({
    data: {
        currentLocation: null,
        loading: false
    },

    onLoad() {
        // 页面加载时获取当前位置
        this.getCurrentLocation();
    },

    // 获取当前位置
    getCurrentLocation() {
        if (app.globalData.userLocation) {
            this.setData({
                currentLocation: app.globalData.userLocation
            });
        } else {
            wx.getLocation({
                type: 'gcj02',
                success: (res) => {
                    const location = {
                        latitude: res.latitude,
                        longitude: res.longitude
                    };
                    this.setData({
                        currentLocation: location
                    });
                    app.globalData.userLocation = location;
                },
                fail: () => {
                    wx.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    });
                }
            });
        }
    },

    // 拍照
    takePhoto() {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            camera: 'back',
            success: (res) => {
                const tempFilePath = res.tempFiles[0].tempFilePath;
                this.uploadImage(tempFilePath);
            },
            fail: () => {
                wx.showToast({
                    title: '拍照失败',
                    icon: 'none'
                });
            }
        });
    },

    // 选择图片
    chooseImage() {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album'],
            success: (res) => {
                const tempFilePath = res.tempFiles[0].tempFilePath;
                this.uploadImage(tempFilePath);
            },
            fail: () => {
                wx.showToast({
                    title: '选择图片失败',
                    icon: 'none'
                });
            }
        });
    },

    // 使用当前定位
    useCurrentLocation() {
        if (!this.data.currentLocation) {
            wx.showToast({
                title: '请先获取位置信息',
                icon: 'none'
            });
            this.getCurrentLocation();
            return;
        }

        this.queryByLocation(this.data.currentLocation);
    },

    // 上传图片并查询
    uploadImage(filePath) {
        this.setData({ loading: true });

        const uploadTask = wx.uploadFile({
            url: `${app.globalData.apiBaseUrl}/api/bus-station/upload-image`,
            filePath: filePath,
            name: 'file',
            formData: {
                'fallback_lat': this.data.currentLocation?.latitude || '',
                'fallback_lng': this.data.currentLocation?.longitude || ''
            },
            success: (res) => {
                try {
                    const data = JSON.parse(res.data);
                    if (data.status === 'success') {
                        this.navigateToResult(data);
                    } else {
                        wx.showToast({
                            title: data.message || '查询失败',
                            icon: 'none'
                        });
                    }
                } catch (e) {
                    wx.showToast({
                        title: '数据解析失败',
                        icon: 'none'
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                });
            },
            complete: () => {
                this.setData({ loading: false });
            }
        });

        // 显示上传进度
        uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress);
        });
    },

    // 根据位置查询
    queryByLocation(location) {
        this.setData({ loading: true });

        wx.request({
            url: `${app.globalData.apiBaseUrl}/api/bus-station/by-location`,
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                latitude: location.latitude,
                longitude: location.longitude,
                address: location.address || '当前位置'
            },
            success: (res) => {
                if (res.data.status === 'success') {
                    this.navigateToResult(res.data);
                } else {
                    wx.showToast({
                        title: res.data.message || '查询失败',
                        icon: 'none'
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            },
            complete: () => {
                this.setData({ loading: false });
            }
        });
    },

    // 跳转到结果页面
    navigateToResult(data) {
        wx.navigateTo({
            url: `/pages/result/result?data=${encodeURIComponent(JSON.stringify(data))}`
        });
    }
});
